package com.intelligent.controller;

import com.intelligent.entity.Permission;
import com.intelligent.entity.Role;
import com.intelligent.entity.RolePermission;
import com.intelligent.service.PermissionService;
import com.intelligent.service.RolePermissionService;
import com.intelligent.service.TRoleService;
import com.intelligent.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色权限管理控制器
 */
@RestController
@RequestMapping("/role")
public class RolePermissionController {

    @Autowired
    private TRoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 获取所有角色列表
     */
    @GetMapping("/roles")
    public Result<List<Role>> getAllRoles() {
        List<Role> roles = roleService.list();
        return Result.success(roles);
    }

    /**
     * 获取所有权限列表
     */
    @GetMapping("/all-permissions")
    public Result<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionService.list();
        return Result.success(permissions);
    }

    /**
     * 获取指定角色的权限ID列表（路径参数格式）
     */
    @GetMapping("/permissions/{roleId}")
    public Result<List<Long>> getRolePermissions(@PathVariable Long roleId) {
        // 查询该角色的所有权限关联记录
        List<RolePermission> rolePermissions = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        
        // 提取权限ID列表
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        
        return Result.success(permissionIds);
    }
    
    /**
     * 获取指定角色的权限ID列表（查询参数格式）
     */
    @GetMapping("/permissions")
    public Result<List<Long>> getRolePermissionsByParam(@RequestParam("roleId") Long roleId) {
        // 查询该角色的所有权限关联记录
        List<RolePermission> rolePermissions = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        
        // 提取权限ID列表
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        
        return Result.success(permissionIds);
    }

    /**
     * 更新角色权限（PUT /role/permissions）
     */
    @PutMapping("/permissions")
    public Result<Void> updateRolePermissionsByPut(@RequestBody Map<String, Object> requestMap) {
        Object roleIdObj = requestMap.get("roleId");
        Object permissionIdsObj = requestMap.get("permissionIds");
        
        if (roleIdObj == null) {
            return Result.error("角色ID不能为空");
        }
        
        Long roleId = Long.valueOf(roleIdObj.toString());
        List<Long> permissionIds = new ArrayList<>();
        
        if (permissionIdsObj instanceof List) {
            List<?> list = (List<?>) permissionIdsObj;
            for (Object item : list) {
                if (item != null) {
                    permissionIds.add(Long.valueOf(item.toString()));
                }
            }
        }
        
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 更新角色权限
     */
    @PostMapping("/update-permissions/{roleId}")
    public Result<Void> updateRolePermissions(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        // 先删除该角色的所有权限关联
        rolePermissionService.lambdaUpdate()
                .eq(RolePermission::getRoleId, roleId)
                .remove();
        
        // 如果权限ID列表不为空，则重新添加权限关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            
            for (Long permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissions.add(rolePermission);
            }
            
            rolePermissionService.saveBatch(rolePermissions);
        }
        
        return Result.success();
    }

    /**
     * 保存角色权限（PUT方法）
     */
    @PutMapping("/permissions/{roleId}")
    public Result<Void> savePermissions(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 保存角色权限（PUT方法 - 兼容不同路径）
     */
    @PutMapping("/update-permissions/{roleId}")
    public Result<Void> savePermissionsByUpdate(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 保存角色权限（PUT方法 - 通用保存接口）
     */
    @PutMapping("/save-permissions/{roleId}")
    public Result<Void> saveRolePermissions(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 保存角色权限（PUT方法 - 兼容save路径）
     */
    @PutMapping("/save/{roleId}")
    public Result<Void> savePermissionsBySave(@PathVariable Long roleId, @RequestBody List<Long> permissionIds) {
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 保存权限（PUT方法 - 通用保存接口）
     */
    @PutMapping("/permissions/save")
    public Result<Void> savePermissionsByPutGeneral(@RequestBody Map<String, Object> requestMap) {
        Object roleIdObj = requestMap.get("roleId");
        Object permissionIdsObj = requestMap.get("permissionIds");
        
        if (roleIdObj == null) {
            return Result.error("角色ID不能为空");
        }
        
        Long roleId = Long.valueOf(roleIdObj.toString());
        List<Long> permissionIds = new ArrayList<>();
        
        if (permissionIdsObj instanceof List) {
            List<?> list = (List<?>) permissionIdsObj;
            for (Object item : list) {
                if (item != null) {
                    permissionIds.add(Long.valueOf(item.toString()));
                }
            }
        }
        
        return updatePermissions(roleId, permissionIds);
    }

    /**
     * 通用的权限更新逻辑
     */
    private Result<Void> updatePermissions(Long roleId, List<Long> permissionIds) {
        // 先删除该角色的所有权限关联
        rolePermissionService.lambdaUpdate()
                .eq(RolePermission::getRoleId, roleId)
                .remove();
        
        // 如果权限ID列表不为空，则重新添加权限关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            
            for (Long permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissions.add(rolePermission);
            }
            
            rolePermissionService.saveBatch(rolePermissions);
        }
        
        return Result.success();
    }

    /**
     * 测试接口 - 初始化角色权限
     */
    @PostMapping("/init-test-data")
    public Result<Void> initTestData() {
        // 创建一个测试角色
        Role adminRole = new Role();
        adminRole.setRoleName("超级管理员");
        adminRole.setDescription("拥有所有权限的超级管理员角色");
        roleService.save(adminRole);
        
        // 获取所有权限ID
        List<Permission> allPermissions = permissionService.list();
        List<Long> allPermissionIds = allPermissions.stream()
                .map(Permission::getPermissionId)
                .collect(Collectors.toList());
        
        // 为超级管理员角色分配所有权限
        List<RolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId : allPermissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(adminRole.getRoleId());
            rolePermission.setPermissionId(permissionId);
            rolePermissions.add(rolePermission);
        }
        
        rolePermissionService.saveBatch(rolePermissions);
        
        return Result.success();
    }
}